package com.example.hzcf.borrowmoney.jpush;

import android.content.Context;

import com.example.hzcf.borrowmoney.appliction.App;
import com.example.hzcf.borrowmoney.utils.LogUtil;
import com.example.hzcf.borrowmoney.utils.SharedpUtil;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by zrb on 2016/10/12.
 */

public class MyJPush {
    private java.lang.String TAG = "jpush";
    private String logs = "";
    TagAliasCallback tagAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int i, String s, Set<String> set) {
            LogUtil.e("code=" + i + "----alias=" + s + "----tags=" );
            switch (i) {
                case 0:
                    logs = "Set tag and alias success";
                    LogUtil.i(TAG, logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    if(!LogUtil.isDebug)
                    SharedpUtil.put(App.getApplication(), SharedpUtil.FileName.assist, SharedpUtil.KEY_ASSIST_JPUSH_ALIAS_AND_TAGS, true);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtil.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
//                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + i;
                    LogUtil.e(TAG, logs);
            }
        }
    };

    /**
     * 设置 别名 和 标签
     *
     * @param context
     * @param alias
     * @param tags
     */
    public void setJpushAliasAndTags(Context context, String alias, Set<String> tags) {
        if ((boolean) SharedpUtil.get(context, SharedpUtil.FileName.assist, SharedpUtil.KEY_ASSIST_JPUSH_ALIAS_AND_TAGS, false)) {
            LogUtil.i(TAG, "已设置alias和tags");
            return;
        }
        if (LogUtil.isDebug) {
            if (tags == null)
                tags = new HashSet<>();
            tags.add("test");
        }
        JPushInterface.setAliasAndTags(context, alias, tags, tagAliasCallback);

    }

    public void toggleJPush(Context context, boolean enable) {
        //需要 ApplicationContext；
        boolean isPushStopped = JPushInterface.isPushStopped(context.getApplicationContext());
        if (enable = true && isPushStopped)
            JPushInterface.resumePush(context.getApplicationContext());
        else {
            if (!isPushStopped)
                JPushInterface.stopPush(context.getApplicationContext());
        }

    }
}

